<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <!-- import CSS -->
  <link rel="stylesheet" href="https://yarnpkg.com/en/package/normalize.css">
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <style lang="stylus">
  html,
  body,
  #app {
    width: 99%;
    height: 99%;
  }
  #image {
    width: 100%;
    height: 99%;
  }
  .el-main {
  }
  .el-container {
    height: 100%;
  }
  .filter-tree {
    max-height: 60%;
    overflow: auto;
    width: 100%;
  }
  .filter-tree>.el-tree-node {
    width: 200%
  }
  .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
    background-color: #e5f4ce;
  }
  </style>
</head>
<body>
  <div id="app">
    <el-container>
      <el-aside width="50%">
        <el-upload
          class="upload-demo"
          action="/json/jdlayout"
          :on-change="handleChange"
          :on-success="uploadSuccess"
          multiple
          :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="refreshData">刷新数据</el-button>
          <div slot="tip" class="el-upload__tip">只能上传json和图片文件</div>
        </el-upload>
        <el-input
          placeholder="输入关键字进行过滤"
          clearable
          v-model="filterText">
        </el-input>
        <el-tree
          class="filter-tree"
          :data="data"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          node-key="aid"
          :filter-node-method="filterNode"
          @current-change="treeNodeChange"
          :highlight-current="true"
          show-checkbox
          ref="tree">
        </el-tree>
        <el-input
          type="textarea"
          :rows="10"
          placeholder="请输入内容"
          :readonly="true"
          v-model="textarea">
        </el-input>
      </el-aside>
      <el-main>
        <canvas id="image" v-if="useCanvas"></canvas>
        <el-image id="image"
          :src="imageUrl"
          fit="scale-down"
          @load="imageLoad" v-else></el-image>
      </el-main>
    </el-container>
  </div>
</body>
  <!-- import Vue before Element -->
  <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
  <!-- import JavaScript -->
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    new Vue({
      el: '#app',
      data: function() {
        return {
          filterText: '',
          data: [],
          defaultProps: {
            children: 'childs',
            label: function(data, node) {
              if (!data.aid) {
                const vue = this.Vue.getCurrentInstance().proxy.$root
                data.aid = vue.nodeIndex++
              }
              let msg = data.className
              if (data.content) msg += '|' + data.content
              if (data.id) msg += '|' + data.id
              return msg
            }
          },
          fileList:[],
          textarea: '',
          imageUrl: 'https://img.bizhizu.com/2014/0710/20140710105229248.jpg.source.jpg',
          imageObj: null,
          useCanvas: true,
          scale:1,
          rect: [],
          drawRect: true,
          intervalId:'',
          nodeIndex:1,
          clickPoint: null
        }
      },
      watch: {
        filterText(val) {
          this.$refs.tree.filter(val);
        }
      },
      methods: {
        filterNode(value, data) {
          if (!value) return true;
          if (value.startsWith('{') && value.endsWith('}')) {
            let obj = this.clickPoint
            let right = data.boundsInfo.right
            let top = data.boundsInfo.top
            let left = data.boundsInfo.left
            let bottom = data.boundsInfo.bottom
            return left <= obj.x && obj.x <= right && top <= obj.y && obj.y <= bottom
          }
          return data.className.indexOf(value) > -1 || data.content.indexOf(value) > -1 || (data.id && data.id.indexOf(value) > -1)
        },
        handleChange(file, fileList) {
        },
        imageLoad() {
          let img = document.getElementById('image')
          img.onclick= this.imgClick
        },
        uploadSuccess(response, file, fileList) {
          if (file.name.endsWith('.json')) {
            this.loadUIobjects(response.jsonUrl)
            if (this.useCanvas) {
              this.showImgInCanvas(response.imageUrl)
            } else {
              this.imageUrl = response.imageUrl
            }
          }
        },
        refreshData() {
          this.loadUIobjects('/json/uiobjects')
          if (this.useCanvas) {
            this.showImgInCanvas('/json/image')
          } else {
            this.imageUrl = '/json/image'
          }
        },
        showImgInCanvas(url) {
            let myCanvas = document.getElementById('image')
            let ctx = myCanvas.getContext("2d")
            let img = new Image()
            img.src = url
            img.onload = () => {
              let width = img.width, height=img.height
              if (width > myCanvas.width) {
                let a = myCanvas.scrollWidth/width
                let b = myCanvas.scrollHeight/height
                this.scale = a<b?a:b
                this.scale = this.scale.toFixed(2)
                width *= this.scale
                height *= this.scale
                width = Number.parseInt(width)
                height = Number.parseInt(height)
              }
              let style = 'width:'+width+'px;height:'+height+'px;'
              myCanvas.setAttribute("width", width)
              myCanvas.setAttribute("height", height) //重新设置画布的大小
              myCanvas.setAttribute("style", style)
              // let lst = this.aspectFit(img.width, img.height, myCanvas.width, myCanvas.height)
              ctx.drawImage(img, 0,0,width, height)
              // let pattern=ctx.createPattern(img,'no-repeat')
              // ctx.fillStyle=pattern
            }
            this.imageObj = img
            myCanvas.onclick = this.imgClick
        },
        aspectFit(imageWidth, imageHeight, canvasWidth, canvasHeight) {
          const imageRate = imageWidth / imageHeight
          const canvasRate = canvasWidth / canvasHeight
          let [dx, dy, dw, dh] = []
          if (imageRate >= canvasRate) {
            dw = canvasWidth
            dh = canvasWidth / imageRate
          } else {
            dh = canvasHeight
            dw = canvasHeight * imageRate
          }
          dx = (canvasWidth - dw) / 2
          dy = (canvasHeight - dh) / 2
          return [dx, dy, dw, dh]
        },
        imgClick(a1) {
            let msg = 'point:(1x,2x) size:(3x,4x) orgSize:(5x,6x)'
            let x=0,y=0
            if (!this.useCanvas) {
              msg = msg.replace('1x', a1.offsetX).replace('2x', a1.offsetY)
              msg = msg.replace('3x', a1.srcElement.clientWidth).replace('4x', a1.srcElement.clientHeight)
              msg = msg.replace('5x', a1.srcElement.naturalWidth).replace('6x', a1.srcElement.naturalHeight)
            } else {
              let myCanvas = document.getElementById('image')
              msg = msg.replace('1x', a1.offsetX).replace('2x', a1.offsetY)
              msg = msg.replace('3x', myCanvas.width).replace('4x', myCanvas.height)
              msg = msg.replace('5x', this.imageObj.width).replace('6x', this.imageObj.height)
              x=a1.offsetX/this.scale, y = a1.offsetY/this.scale
            }
            x = Number.parseInt(x)
            y = Number.parseInt(y)
            this.clickPoint = {x,y}
            this.filterText = JSON.stringify(this.clickPoint)
            console.log(msg)
        },
        loadUIobjects(url) {
            axios.get(url).then((rsp) =>{
              this.data = rsp.data
            })
        },
        treeNodeChange(data, node) {
          let obj = {}
          let keys = Object.keys(data)
          for (let k in keys) {
            k = keys[k]
            if (k == 'childs') continue
            obj[k] = data[k]
          }
          this.textarea = JSON.stringify(obj, null, 2)
          let right = data.boundsInfo.right*this.scale
          let top = data.boundsInfo.top*this.scale
          let left = data.boundsInfo.left*this.scale
          let bottom = data.boundsInfo.bottom*this.scale
          this.rect = [right, top, (left-right), (bottom-top)]
          if (this.intervalId)
            clearInterval(this.intervalId)
          this.intervalId = setInterval(this.drawRectFlash, 1000)
          this.drawRect = true
        },
        drawRectFlash() {
          let myCanvas = document.getElementById('image')
          let ctx = myCanvas.getContext("2d")
          if (this.drawRect) {
            ctx.strokeStyle = "#F00"
            ctx.strokeRect(this.rect[0],this.rect[1],this.rect[2],this.rect[3])
          } else {
            ctx.drawImage(this.imageObj, 0,0,this.imageObj.width*this.scale, this.imageObj.height*this.scale)
          }
          this.drawRect = !this.drawRect
        }
      }
    })
  </script>
</html>